package cn.com.guage.guc.readwrite;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

//未加读写锁的时候，线程会抢占进行并发操作
class MyCache2 {
    //创建map集合
    private volatile Map<String,Object> map = new HashMap<>();

    //放数据
    public void put(String key,Object value) {

        try {
            System.out.println(Thread.currentThread().getName()+" 正在写操作"+key);
            //暂停一会
            TimeUnit.MICROSECONDS.sleep(300);
            //放数据
            map.put(key,value);
            System.out.println(Thread.currentThread().getName()+" 写完了"+key);
        } catch (Exception e) {
            e.printStackTrace();
        } 
    }

    //取数据
    public Object get(String key) {
        Object result = null;
        try {
            System.out.println(Thread.currentThread().getName()+" 正在读取操作"+key);
            //暂停一会
            TimeUnit.MICROSECONDS.sleep(300);
            result = map.get(key);
            System.out.println(Thread.currentThread().getName()+" 取完了"+key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}

public class ReadWriteLockDemo2 {
    public static void main(String[] args) throws InterruptedException {
    	MyCache2 myCache = new MyCache2();
        //创建线程放数据
        for (int i = 1; i <=35; i++) {
            final int num = i;
            new Thread(()->{
                myCache.put(num+"",num+"");
            },String.valueOf(i)).start();
        }

        TimeUnit.MICROSECONDS.sleep(300);

        //创建线程取数据
        for (int i = 1; i <=35; i++) {
            final int num = i;
            new Thread(()->{
                myCache.get(num+"");
            },String.valueOf(i)).start();
        }
    }
}
